using System.ComponentModel;
using System.Text.Json;
using System.Windows.Forms;

namespace PlexMediaLinker
{
    // 全局配置管理
    public static class Config
    {
        private const string ConfigPath = "config.json";
        public static BindingList<GroupConfig> Groups { get; private set; } = [];
        public static bool GlobalAutoStart { get; set; }
        public static bool AutoSyncEnabled { get; set; } = false;
        public static int AutoSyncIntervalMinutes { get; set; } = 60;

        public static void Load()
        {
            if (File.Exists(ConfigPath))
            {
                try
                {
                    var json = File.ReadAllText(ConfigPath);
                    using var doc = JsonDocument.Parse(json);
                    var root = doc.RootElement;
                    // 读取开机自启
                    GlobalAutoStart = root.GetPropertyOrDefault("GlobalAutoStart", false);
                    // 读取定时同步设置
                    AutoSyncEnabled = root.GetPropertyOrDefault("AutoSyncEnabled", false);
                    AutoSyncIntervalMinutes = root.GetPropertyOrDefault("AutoSyncIntervalMinutes", 60);
                    // 读取组列表
                    var list = root.GetPropertyOrDefault("Groups", Array.Empty<JsonElement>());
                    var cfgs = list.Select(el => JsonSerializer.Deserialize<GroupConfig>(el.GetRawText())!)
                                  .Where(cfg => cfg != null)
                                  .ToList();
                    Groups = new BindingList<GroupConfig>(cfgs);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"配置文件加载失败: {ex.Message}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Groups = [];
                    GlobalAutoStart = false;
                }
            }
            else
            {
                Groups = [];
                GlobalAutoStart = false;
            }
            Groups.ListChanged += (s, e) => Save();
        }

        public static void Save()
        {
            var obj = new
            {
                GlobalAutoStart,
                AutoSyncEnabled, AutoSyncIntervalMinutes,
                Groups = Groups.ToList()
            };
            var json = JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(ConfigPath, json);
            // 更新注册表自启
            AutoStartManager.SetAutoStart(GlobalAutoStart);
        }
    }

}
